﻿using AnQinFrameWorkAPI.DataBase;
using AnQinFrameWorkAPI.Entity.Blog.DTO.BlogUser;
using AnQinFrameWorkAPI.Entity.Blog.Entity;
using AnQinFrameWorkAPI.Entity.Blog.View.BlogUser;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using FrameWork.DataHelper;
using FrameWork.Entity;
using FrameWork.JWT;
using FrameWork.Request;
using Microsoft.EntityFrameworkCore;

namespace AnQinFrameWorkAPI.Service.Blog;

/// <summary>
///     博客用户业务层
/// </summary>
public class BlogUserService
{
    //数据库
    private readonly DatabaseContext _context;

    //自动映射
    private readonly IMapper _mapper;

    //解密Token
    private readonly IUserContext _userContext;

    //构造注入
    public BlogUserService(DatabaseContext context, IMapper mapper, IUserContext userContext)
    {
        _context = context;
        _mapper = mapper;
        _userContext = userContext;
    }

    #region 获取博客用户列表

    public async Task<RequestResponseModel> GetBlogUserList(BlogUserSearchDTO blogUserSearchDTO)
    {
        //筛选
        var query = _context.BlogUser
                .ProjectTo<BlogUserView>(_mapper.ConfigurationProvider)
                .AsNoTracking().WhereIF(a => a.Code.Contains(blogUserSearchDTO.Code),
                    !string.IsNullOrEmpty(blogUserSearchDTO.Code))
                .WhereIF(a => a.Name.Contains(blogUserSearchDTO.Name), !string.IsNullOrEmpty(blogUserSearchDTO.Name))
                .WhereIF(a => a.Email.Contains(blogUserSearchDTO.Email), !string.IsNullOrEmpty(blogUserSearchDTO.Email))
                .WhereIF(a => a.CreateTime > blogUserSearchDTO.StartTime, blogUserSearchDTO.StartTime != null)
                .WhereIF(a => a.CreateTime < blogUserSearchDTO.EndTime, blogUserSearchDTO.EndTime != null)
            ;

        //返回列表
        var blogUserList = await query
            .OrderBy(a => a.CreateTime)
            .Page(blogUserSearchDTO.PageIndex, blogUserSearchDTO.PageSize)
            .ToListAsync();

        //总数据量
        var pageCount = await query.CountAsync();

        //返回数据
        var pageResult = new PageResult<BlogUserView>(blogUserList, pageCount);
        return RequestResponse.OK(pageResult, "查询成功");
    }

    #endregion

    #region 新增博客用户

    public async Task<RequestResponseModel> AddBlogUser(BlogUserAddDTO blogUserAddDTO)
    {
        //生成新数据
        var blogUser = _mapper.Map<BlogUserModel>(blogUserAddDTO);

        blogUser.Id = Guid.NewGuid();
        blogUser.CreateTime = DateTime.Now;

        //新增数据
        _context.BlogUser.Add(blogUser);
        await _context.SaveChangesAsync();

        return RequestResponse.OK(blogUser.Id, "新增成功");
    }

    #endregion

    #region 更新博客用户

    public async Task<RequestResponseModel> PutBlogUser(BlogUserUpdateDTO blogUserUpdateDTO)
    {
        //校验数据
        var query = await Valid.ValidId(_context.BlogUser, blogUserUpdateDTO.Id);
        if (query == null) return RequestResponse.ErrorRequest("博客用户Id无效");
        ;

        //编辑数据
        var blogUser = _mapper.Map(blogUserUpdateDTO, query);

        //更新表
        _context.BlogUser.Update(blogUser);
        await _context.SaveChangesAsync();

        return RequestResponse.OK(blogUserUpdateDTO.Id);
    }

    #endregion

    #region 删除博客用户

    public async Task<RequestResponseModel> DeleteBlogUser(SingleIdDTO deleteDTO)
    {
        //校验数据
        var query = await Valid.ValidId(_context.BlogUser, deleteDTO.Id);
        if (query == null) return RequestResponse.ErrorRequest("博客用户Id无效");
        ;

        //删除操作
        _context.BlogUser.Remove(query);

        //保存库
        await _context.SaveChangesAsync();
        return RequestResponse.OK(deleteDTO.Id, "删除成功");
    }

    #endregion

    #region 根据Token获取用户信息

    public async Task<RequestResponseModel> BlogHandShake()
    {
        //sql
        var sql = @"
                SELECT
                    Id,
                    Code,
                    Name,
                    SuperiorId,
                    SuperiorName,
                    Order,
                    IsDelete,
                    CreateTime
                FROM
                    Department
                WHERE
                    IsDelete = 0
            ";

        var userId = _userContext.UserId;
        //查找账号
        var query = await _context.Database.SqlQueryRaw<BlogUserView>(sql)
            .AsQueryable().FirstOrDefaultAsync(a => a.Id.ToString() == userId);

        //找不到账号
        if (query == null) return RequestResponse.Unauthorized("找不到该博客用户", userId);

        //返回Token
        return RequestResponse.OK(query, "验证成功");
    }

    #endregion
}